package model.impl.menu;

import model.EMenuState;
import model.impl.StateListener;

public class SettingsState extends AbstractMenuState {
	private static final SettingsState INSTANCE = new SettingsState();
	
	private static final int ALTERNATIVE_IP 		= 0;
	private static final int ALTERNATIVE_NICK 		= 1;
	private static final int ALTERNATIVE_FULLSCREEN	= 2;
	private static final int ALTERNATIVE_BACK		= 3;
	
	private boolean fullScreen;
	private String ipAddress;
	private String nickName;
	
	private SettingsState() {
		currentAlternative = 0;
		numberOfAlternatives = 4;
		
		ipAddress = "127.0.0.1";
		nickName = "Player";
		fullScreen = false;
	}
	
	public static SettingsState getInstance() {
		return INSTANCE;
	}
	
	@Override
	public void fireAlternative() {
		if (currentAlternative == ALTERNATIVE_FULLSCREEN) {
			fullScreen = !fullScreen;
			setFullScreen();
		} else if (currentAlternative == ALTERNATIVE_BACK) {
			viewMainMenu();
		}
	}

	private void setFullScreen() {
		for (StateListener listener : listeners) {
			listener.setFullScreen(fullScreen);
		}
	}

	@Override
	public int getChosenCharacterIndex() {
		return 0;
	}

	@Override
	public String getIP() {
		return ipAddress;
	}

	@Override
	public String getNick() {
		return nickName;
	}

	@Override
	public boolean isFullScreen() {
		return fullScreen;
	}

	private void viewMainMenu() {
		for (StateListener listener : listeners) {
			listener.viewMainMenu();
		}
	}

	@Override
	public void insertCharacter(char c) {
		if (currentAlternative == ALTERNATIVE_IP) {
			ipAddress = ipAddress + c;
			ipAddressChanged();
		} else if (currentAlternative == ALTERNATIVE_NICK) {
			nickName = nickName + c;
			nickNameChanged();
		}
	}

	@Override
	public void removeCharacter() {
		if (currentAlternative == ALTERNATIVE_IP) {
			if (!ipAddress.isEmpty()) {
				ipAddress = ipAddress.substring(0, ipAddress.length() - 1);
				ipAddressChanged();
			}
		} else if (currentAlternative == ALTERNATIVE_NICK) {
			if (!nickName.isEmpty()) {
				nickName = nickName.substring(0, nickName.length() - 1);
				ipAddressChanged();
			}			
		}
	}

	@Override
	public EMenuState getEMenuState() {
		return EMenuState.SETTINGS;
	}

	@Override
	public void moveAlternativeLeft() {
		
	}

	@Override
	public void moveAlternativeRight() {
		
	}
	
	private void ipAddressChanged() {
		for (StateListener listener : listeners) {
			listener.serverAddressChanged(ipAddress);
		}
	}
	
	private void nickNameChanged() {
		for (StateListener listener : listeners) {
			listener.nickNameChanged(nickName);
		}
	}
}
